#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys,os,getpass

def goods_list_show(my_dict):
    local_dict = {}
    i = 1
    print('编号\t','商品名称\t','商品价格(元)\t','商品总数量(个)\t','商品剩余数量(个)\t')
    for index in my_dict:
        item = my_dict[index]
        if type(item) is dict:
            print('%-5d  %-20s  %-10d  %-10d  %-10d' % (i,index,item['price'],item['sum'],item['num']))
            local_dict[i] = [index,item['price'],item['num'],item['sum']]
        i += 1
    return local_dict

def cart_goods_show(show_dict):
    show_all_sum = 0
    show_all_num = 0
    print('编号\t','商品名称\t','商品价格(元)\t','商品总数量(个)\t','购买数量(个)\t','购买金额（元)\t')
    for index in show_dict:
        item = show_dict[index]
        if type(item) is list:
            print('%-5s \t %-20s \t %-10d \t %-10d \t %-10d \t %-10d' % (index,item[0],item[1],item[2],item[3],item[4]))
            show_all_sum += item[4]
            show_all_num += 1
    print('请确认您购买商品，总金额：%d（元）'.center(84,'-') % show_all_sum)
    return (show_all_sum,show_all_num)

def shopping_cart_show(my_cart,my_goods_dict):
    print('欢迎来到您的购物车'.center(80,'#'))
    goods_all_sum = 0
    goods_all_num = 0
    if my_cart:
        (goods_all_sum,goods_all_num)  = cart_goods_show(my_cart)
    else:
        print('当前您的购物车为空'.center(80,' '))
    return (goods_all_sum,goods_all_num,my_goods_dict)

def user_billing(billing_list,my_cart,billing_balance):
    print('欢迎来到结算'.center(80,'#'))
    if my_cart:
        cart_goods_show(my_cart)
        billing_file = open('userinfo.txt','w')
        for user_info in billing_list:
            billing_file.writelines(user_info)
        billing_file.close()
        sys.exit('结帐成功，你当前余额 ：%d'.center(80,' ') % billing_balance)
    else:
        print('当前您的购物车为空'.center(80,' '))

goods_list = {
    'iphone': {'price':5800,'num':5,'sum':5},
    'xiaomi': {'price':1000,'num':5,'sum':5},
    'huawei': {'price':3000,'num':5,'sum':5},
    'meizu': {'price':1500,'num':5,'sum':5},
    'oppo': {'price':2000,'num':5,'sum':5},
    'vivo': {'price':2500,'num':5,'sum':5},
}
i = 0
while i < 3:
    username = input('请输入用户名：')
    password = input('请输入密码：')
    user_file = open('userinfo.txt','r')
    user_list = user_file.readlines()
    user_file.close()
    for user_line in user_list:
        (user,passwd,init_balance) = user_line.strip('\n').split()
        init_balance = int(init_balance)
        now_balance = init_balance
        my_goods_sum = 0
        if username == user and password == passwd:
            user_shopping_cart = {}
            user_shopping_cart_count = 0
            line_num = user_list.index(user_line)
            first_flag = 1
            while first_flag:
                print("欢迎登录购物系统".center(50,'-'))
                goods_output_dict = goods_list_show(goods_list)
                goods_index = input('输入商品编号(1-6) | 购物车(c)| 结帐(b) | 退出(q) : ')
                if len(goods_index) != 0 and goods_index.isdigit():
                    goods_index = int(goods_index)
                if goods_index == 'q':
                    sys.exit(0)
                elif goods_index == 'c':
                    (my_goods_sum,user_shopping_cart_count,goods_list) = shopping_cart_show(user_shopping_cart,goods_list)
                    now_balance = init_balance - my_goods_sum
                    if now_balance < 0:
                        print('您的余额不足，请及时充值，谢谢')
                        time.sleep(2)
                elif goods_index == 'b':
                    user_list[line_num] = user + ' ' + passwd + ' ' + repr(now_balance) + '\n'
                    user_billing(user_list,user_shopping_cart,now_balance)
                elif goods_index in goods_output_dict:
                    (goods_name,goods_price,goods_num) = (goods_output_dict[goods_index][0], goods_output_dict[goods_index][1], goods_output_dict[goods_index][2])
                    print('【 编号：%-5d \t 名称：%-15s \t 价格：%-5d（元） \t 数量：%-5d（个）】' % (goods_index,goods_name,goods_price,goods_num))

                    second_flag = 1
                    while second_flag:
                        buy_num = input('请输入购买商品个数(最大值为%d) | 返回(b) | 退出(q): ' % goods_num)
                        if len(buy_num) != 0 and buy_num.isdigit():
                            buy_num = int(buy_num)
                        if buy_num == 'q':
                            sys.exit(0)
                        elif buy_num == 'b':
                            break
                        elif type(buy_num) is int and buy_num > 0 and buy_num <= goods_num:
                            my_goods_sum = goods_price * buy_num
                            if my_goods_sum <= now_balance:
                                print('购买商品 %s 总价格为 : %d' % (goods_name,my_goods_sum))
                                add_flag = input('请确认是否加入购物车（y | n）：')
                                if add_flag == 'y':
                                    if goods_index not in user_shopping_cart:
                                        user_shopping_cart_count += 1
                                        user_shopping_cart[goods_index] = [goods_name,goods_price,goods_num,buy_num,my_goods_sum]
                                    else:
                                        user_shopping_cart[goods_index][3] += buy_num
                                        user_shopping_cart[goods_index][4] += my_goods_sum
                                    now_balance -= my_goods_sum
                                    goods_list[goods_name]['num'] -= buy_num
                                    second_flag = 0
                                else:
                                    break
                            else:
                                print('您的余额不足，请重新选择，谢谢')
                        else:
                            pass
                else:
                    pass
    else:
        if i != 2:
            print('用户或密码错误，请重新输入')
    i += 1
else:
    sys.exit('用户或密码输入错误超过三次，退出系统')
